package org.easy.excel.aop.cell.inner;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.easy.excel.aop.cell.CellInterceptorAdapter;
import org.easy.excel.aop.cell.CellJoinPoint;
import org.easy.excel.exception.ExcelException;

/**
 * 处理pattern标签(日期)
 * @author lisuo
 *
 */
public class PatternCellInterceptor extends CellInterceptorAdapter {

	@Override
	public boolean supports(CellJoinPoint joinPoint) {
		return joinPoint.getFieldValue().getPattern() != null && joinPoint.getValue() != null;
	}

	@Override
	public Object executeImport(CellJoinPoint joinPoint) throws ExcelException {
		if(joinPoint.getValue() instanceof Date) {
			return joinPoint.getValue();
		}
		String pattern = joinPoint.getFieldValue().getPattern();
		String[] patterns = StringUtils.split(pattern, ",");
		String str = joinPoint.getValue().toString();
		Date date = parseDate(str, patterns);
		if (date == null) {
			throw newExcelDataException("[" + str + "]不能转换成日期,正确的格式应该是[" + pattern + "]", joinPoint);
		}
		return date;
	}

	@Override
	public Object executeExport(CellJoinPoint joinPoint) throws ExcelException {
		if(joinPoint.getValue() instanceof Date) {
			String[] patterns = StringUtils.split(joinPoint.getFieldValue().getPattern(), ",");
			return DateFormatUtils.format((Date) joinPoint.getValue(), patterns[0]);
		}
		return super.executeExport(joinPoint);
	}

	private Date parseDate(String str, String... patterns) {
		if (patterns != null && patterns.length > 0) {
			for (String p : patterns) {
				SimpleDateFormat sdf = new SimpleDateFormat(p);
				try {
					return sdf.parse(str);
				} catch (Exception ignore) {
					continue;
				}
			}
		}
		return null;
	}

}
